package controller;

import dao.*;
import entity.Nurse;
import entity.NurseRole;
import entity.Permission;
import entity.RolePermission;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/login")
@Scope("prototype")
public class loginController {

    @Resource(name = "nurseDao")
    private NurseDao nurseDao;
    @Autowired
    private NurseRoleDao nurseRoleDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;

    @RequestMapping("/login")
    public String login(String call, String pwd, HttpServletRequest request) throws ServletException, IOException {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        UsernamePasswordToken token = new UsernamePasswordToken(call, pwd);
        try {
            subject.login(token);
            Nurse nurse = nurseDao.login(call);
            RolePermission rolePermission = rolePermissionDao.getRolePermissionByPosId(nurse.getPosId());
            System.out.println(nurse.getnId()+"---");
            NurseRole nurseRole = nurseRoleDao.getNurseRoleByNid(nurse.getnId());
            List<Permission> list = permissionDao.query(rolePermission.getPosId());
            request.getSession().setAttribute("list", list);
            return "redirect:/Super.jsp";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }


    }

    @RequestMapping("/outLogin")
    public String outLog(HttpServletRequest request) {
        request.getSession().removeAttribute("list");
        request.getSession().removeAttribute("nurse");
        SimpleAuthenticationInfo info = null;
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        return "redirect:/login.jsp";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("list");
        return "redirect:/login.jsp";
    }



}